/**
 * @file filter
 * @author liaoxuezhi@baidu.com
 */
/* eslint fecs-indent: [0, "space", 2, 2] */

import * as React from 'react';
import {
  PureComponent,
  PropTypes
} from 'react';
import {Enhance as FormItem} from '../form-item';
import * as Sensor from '../../../widgets/visibility-sensor.jsx';
import validationErrors from '../validation-messages';
import * as assign from 'object-assign';


@FormItem({
  type: 'rich-text',
  test: (path, config) => /(?:^|\/)form-item$/.test(path)
  && (config.type === 'editor' || config.type === 'rich-text'),
  filter: config => {
    let validations = config.validations || '';

    if (config.maxLength) {
      validations += (validations ? ',' : '') + `maxLength:${config.maxLength}`
    }

    return assign({
      validations: validations,
      validationErrors
    }, config);
  },
  validateSchema: 'http://amis.baidu.com/schemas/form.json#/definitions/formItem'
})
export default class Editor extends PureComponent {
  static propTypes = {
    className: PropTypes.string,
    formMode: PropTypes.string,
    formHorizontal: PropTypes.object,
    inputClassName: PropTypes.string
  };

  static defaultProps = {
    value: '',
    reciever: '/api/upload/image',
    placeholder: '请输入',
    saveAsUbb: false,
    imageEditable: true,
    editorClass: ''
  };

  constructor(props) {
    super(props);

    this.state = {
      Editor: null
    };

    this.changeValue = this.changeValue.bind(this);
    this.handleVisibleChange = this.handleVisibleChange.bind(this);
  }

  handleVisibleChange(isVisible) {
    if (this.state.Editor || !isVisible) {
      return;
    }

    require(['../../../widgets/editor/froala/editor'], component => this.setState({Editor: component.default}));
  }

  changeValue(value) {
    this.props.setValue(value);
  }

  render() {
    const {
      disabled,
      inputClassName,
      placeholder,
      type,
      reciever,
      saveAsUbb,
      buttons,
      imageEditable,
      editorClass,
      maxLength,
      options,
      size
    } = this.props;

    const commonProps = {
      className: inputClassName,
      disabled,
      type,
      key:"input",
      placeholder,
      name: name,
      onChange: this.changeValue,
      value: this.props.getValue() || '',
      saveAsUbb,
      reciever,
      buttons,
      imageEditable,
      editorClass,
      maxLength,
      options,
      size
    };
    const Editor = this.state.Editor;

    return Editor ? (
        <Editor
          {...commonProps}
        />
      ) : (
        <Sensor onChange={this.handleVisibleChange}>
          <div className="text-center m-t-lg">
            <i className="fa fa-spinner fa-spin fa-3x fa-fw" />
          </div>
        </Sensor>
      );
  }
}
